<?php

namespace App\Http\Controllers;

use App\Models\User;

use Illuminate\Http\Request;
use Validator;
use Hash;
use Auth;

class UsersController extends Controller
{
    protected $layout = "layouts.main";
	
    public function __construct() {
		$this->middleware('auth')->only('dashboard');
		//$this->beforeFilter('auth', array('only'=>array('dashboard')));
	}
	
    public function register() {
       return view('users.register');
    }
	
    public function login() {
       return view('users.login');
    }
	
	public function dashboard(){
		return view('users.dashboard');
	}
	
	public function logout() {
        if(Auth::check())
        { 
            Auth::logout();
        } 
		return redirect('user/login')->with('message','你现在已经退出登录了!'); 
    }
	
	public function create(Request $request){
		$validator = Validator::make($request->all(), User::$rules);
		if ($validator->passes()) {
			$user = new User;//实例化User对象
			$user->username = $request->input('username');
			$user->email = $request->input('email');
			$user->password = Hash::make($request->input('password'));
			$user->save();
			return redirect('user/login')->with('message', '欢迎注册，好好玩耍!');
		} else {
			return redirect('user/register')->with('message', '请您正确填写下列数据')->withErrors($validator)->withInput();
		}
	}
	
    public function signin(Request $request) {
		if (Auth::attempt(array('email'=>$request->input('email'), 'password'=>$request->input('password')))) {
			return redirect('user/dashboard')->with('message', '欢迎登录');
		} else {
			return redirect('user/login')->with('message', '用户名或密码错误')->withInput();
		}
	}
}
